Convert Decimal to Binary

Theory:

To convert a decimal number to binary, we repeatedly divide the decimal number by 2 and note the remainders. The binary representation is obtained by reading the remainders in reverse order.

Python Code:

def decimal_to_binary(decimal):
    binary = ''
    while decimal > 0:
        binary = str(decimal % 2) + binary
        decimal //= 2
    return binary

def convert_and_display_binary():
    decimal = int(input("Enter a decimal number: "))
    binary = decimal_to_binary(decimal)
    print("Binary representation:", binary)


convert_and_display_binary()

Example Output 1:

Enter a decimal number: 10

Binary representation: 1010

Example Output 2:

Enter a decimal number: 27

Binary representation: 11011

Code Explanation:

The function decimal_to_binary(decimal) converts a decimal number to its binary representation by repeatedly dividing by 2 and noting the remainders.

The function convert_and_display_binary() takes input for a decimal number, converts it to binary using the first function, and displays the result.